package org.opens.javaskill.thread.demo.capture;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Stream;

/**
 * @Date 2020/8/15 14:30
 * @Created by 99126
 */
public class CaptureService {

    private final static LinkedList<Control> CONTROLS = new LinkedList<>();

    public static void main(String[] args) {
        List<Thread> worker = new ArrayList<>();
        Stream.of("m1", "m2", "m3", "m4", "m5", "m6", "m7", "m8", "m9", "m10").map(CaptureService::createCaptureThread)
                .forEach(x -> {
                    x.start();
                    worker.add(x);
                });

        worker.stream().forEach(y -> {
            try {
                y.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("main finished");
    }

    public static Thread createCaptureThread(String name) {
        return new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " begin start");
            synchronized (CONTROLS) {
                while ( CONTROLS.size() > 5 ) {
                    System.out.println("由于当前开启线程数量大于5, 为" + CONTROLS.size() + ", 所以" + Thread.currentThread().getName() + "进入休眠");
                    try {
                        CONTROLS.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                CONTROLS.addLast(new Control());
            }
            System.out.println(Thread.currentThread().getName() + " start");
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (CONTROLS) {
                System.out.println(Thread.currentThread().getName() + " end");
                CONTROLS.removeFirst();
                CONTROLS.notifyAll();
            }
        }, name);
    }

    private static class Control {

    }

}
